import { computed, ref, toRaw, type Reactive, type Ref } from "vue";
import { isContainerEle } from "./useUtil"

// 暴露给视图上可以用的一些方法
export default function useExpose(
  models: Reactive<any>,
  itemInfos: Reactive<any>,
  loading: Ref<boolean>
) {
  
  const innerKeys = computed(() => Object.keys(models))

  function getModels(key: string) {
    if (key) {
      return toRaw(models[key])
    }
    return toRaw(models)
  }
  
  function setModels(obj: Record<string, any>) {
    Object.keys(obj).forEach((key) => {
      if (innerKeys.value.includes(key)) {
        models[key] = obj[key]
      }
    })
  }
  
  function updateOptions(obj: Record<string, any>) {
    Object.keys(obj).forEach((key) => {
      if (innerKeys.value.includes(key)) {
        Object.keys(obj[key]).forEach((optionKey) => {
          if (['props', 'events', 'slots'].includes(optionKey)) {
            Object.keys(obj[key][optionKey]).forEach((propKey) => {
              itemInfos[key][optionKey][propKey] = obj[key][optionKey][propKey]
            })
          }
        })
      }
    })
  }

  function changeDisplayFields(keys: string[], flag: boolean = false) {
    for (const key of keys) {
      if (innerKeys.value.includes(key)) {
        if (isContainerEle(itemInfos[key].type)) {
          if (itemInfos[key].options.props) {
            itemInfos[key].options.props['_display'] = flag
          }
        } else if (itemInfos[key].props) {
          itemInfos[key].props['_display'] = flag
        }
      }
    }
  }

  function changeDisabledFields(keys: string[], flag: boolean = false) {
    for (const key of keys) {
      if (innerKeys.value.includes(key) && itemInfos[key].props) {
        if (itemInfos[key].props) {
         itemInfos[key].props['disabled'] = flag
        }
      }
    }
  }
  
  function showLoading() {
    loading.value = true
  }
  
  function hideLoading() {
    loading.value = false
  }

  return {
    getModels,
    setModels,
    updateOptions,
    showLoading,
    hideLoading,
    changeDisplayFields,
    changeDisabledFields
  }
}